package com.im.activity;

import java.util.Collection;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;

import roboguice.inject.InjectView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.core.sdk.core.BaseActivity;
import com.core.sdk.core.BaseEvent;
import com.core.sdk.core.LogUtil;
import com.core.sdk.core.UITask;
import com.core.sdk.utils.ToastUtil;
import com.im.R;
import com.im.event.UserRequestEvent;
import com.im.event.UserRequestEvent.OPERATE;
import com.im.event.UserResponseEvent;
import com.im.service.SmackService;

public class LoginActivity extends BaseActivity implements OnClickListener {

	@InjectView(R.id.act_login_btn_login)
	Button btnLogin;

	@InjectView(R.id.act_login_btn_reg)
	Button btnReg;

	@InjectView(R.id.act_login_et_name)
	EditText etName;

	@InjectView(R.id.act_login_et_pwd)
	EditText etPwd;

	private final int REQUEST_CODE_REGISTER = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		btnLogin.setOnClickListener(this);
		btnReg.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == btnReg) {
			Intent it = new Intent(this, RegisterActivity.class);
			startActivityForResult(it, REQUEST_CODE_REGISTER);
		} else if (v == btnLogin) {
			String username = etName.getText().toString().trim();
			String password = etPwd.getText().toString().trim();
			UserRequestEvent evt = new UserRequestEvent(findLocation(SmackService.class), OPERATE.request_login, username, password);
			sendEvent(evt);
		}
	}

	@Override
	public void executeEvent(BaseEvent evt) {
		super.executeEvent(evt);
		if (evt instanceof UserResponseEvent) {
			UserResponseEvent event = (UserResponseEvent) evt;
			if (event.getResponseCode() == UserResponseEvent.RESPONSE_LOGIN_SUC) {
				procressLoginSuc(event);
			} else if (event.getResponseCode() == UserResponseEvent.RESPONSE_LOGIN_FAI) {
				procressLoginFai();
			}
		}
	}
	
	
	private void procressLoginSuc(UserResponseEvent event) {
		postRunOnUi(new UITask(this) {
			@Override
			public void run() {
				ToastUtil.show(getContext(), "登录成功");
				startActivity(HomeActivity.createIntent(getContext()));
				finish();
			}
		});
	}

	private void procressLoginFai() {
		postRunOnUi(new UITask(this) {
			@Override
			public void run() {
				ToastUtil.show(getContext(), "登录失败");
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != Activity.RESULT_OK) {
			return;
		}
		if (requestCode == REQUEST_CODE_REGISTER) {
			ToastUtil.show(this, "注册成功");
		}
	}

	@Override
	protected int getContentView() {
		return R.layout.act_login;
	}

}
